package com.alibaba.citrus.ots.b2b.trade.order.repository.impl;

import com.alibaba.citrus.ots.b2b.trade.order.repository.OrderLineQueryServiceRepository;
import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.common.constant.SaleOrderConstants;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.platform_enhance.SaleOrderTag;
import com.epoch.app.otsb2btradecenter.domain.order.dto.LoadOrderRequest;
import com.epoch.app.otsb2btradecenter.domain.order.model.Order;
import com.epoch.app.otsb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.LoadOrderLineRequest;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.OrderLineLoadListRequest;
import com.epoch.app.otsb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.otsb2btradecenter.domain.orderline.service.OrderLineService;
import com.epoch.app.otsb2btradecenter.dto.OrderDetailDTO;
import com.epoch.app.otsb2btradecenter.dto.request.OrderLinePageQueryRequest;
import com.epoch.app.otsb2btradecenter.dto.request.QuerySaleOrderLine;
import com.epoch.app.otsb2btradecenter.dto.request.QuerySaleOrderLineRequest;
import com.epoch.app.otsb2btradecenter.dto.response.OrderLinePageQueryResponse;
import com.epoch.app.otsb2btradecenter.enums.OrderStatus;
import com.epoch.app.otsb2btradecenter.enums.OrderTypeStatus;
import com.epoch.app.otsb2btradecenter.model.dto.AmountResponse;
import com.epoch.app.otsb2btradecenter.model.dto.PageQueryOrderLineESListRequest;
import com.epoch.app.otsb2btradecenter.model.dto.QueryOrderLineRequest;
import com.epoch.app.otsb2btradecenter.model.dto.SearchOrderLineListRequest;
import com.epoch.app.otsb2btradecenter.obtcsaleorderlineindex.model.ObtcSaleOrderLineIndex;
import com.epoch.app.otsb2btradecenter.obtcsaleorderlineindex.service.ObtcSaleOrderLineIndexService;
import com.epoch.app.otsforecastsales.api.forecastorderquery.service.ForecastOrderQueryService;
import com.epoch.app.otsforecastsales.cartonspecsquery.service.CartonSpecsQueryService;
import com.epoch.app.otsforecastsales.dto.request.QueryForecastOrderDetailRequest;
import com.epoch.app.otsforecastsales.dto.response.QueryForecastOrderDetailReponse;
import com.epoch.app.otsforecastsales.model.dto.ActivitySDO;
import com.epoch.app.otsplatformenhance.dictionaryquery.service.DictionaryQueryService;
import com.epoch.app.otsplatformenhance.model.dto.QueryDictionaryRequest;
import com.epoch.app.otsplatformenhance.sdo.DictionarySDO;
import com.epoch.app.otspricecenter.api.pricequery.service.PriceQueryService;
import com.epoch.app.otspricecenter.dto.request.*;
import com.epoch.app.otspricecenter.dto.response.PriceQueryResponse;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Component
public class OrderLineQueryServiceRepositoryImpl implements OrderLineQueryServiceRepository {

    //单据原因
    private static final String ORDER_REASON_TYPE = "orderReason";

    //拒绝原因
    private static final String REFUSE_REASON = "refuseReason";

    private static final String ORDER_TIME_START = " 00:00:00";
    private static final String ORDER_TIME_END = " 23:59:59";

    private static final String UPDATE_TIME_START = " 00:00:00";
    private static final String UPDATE_TIME_END = " 23:59:59";

    @Resource
    private OrderLineService orderLineService;

    @Resource
    private OrderService orderService;

    @Resource
    private PriceQueryService priceQueryService;

    @Resource
    private ForecastOrderQueryService forecastOrderQueryService;

    @Resource
    private ObtcSaleOrderLineIndexService obtcSaleOrderLineIndexService;

    @Resource
    private DictionaryQueryService dictionaryQueryService;

    @Autowired
    private CartonSpecsQueryService cartonSpecsQueryService;

    private static Log log = Log.getLogger(OrderLineQueryServiceRepositoryImpl.class);

    @Override
    public PageResult<List<OrderLinePageQueryResponse>> pageQuery(OrderLinePageQueryRequest request) {
        OrderLineLoadListRequest orderLineLoadListRequest = orderLineLoadListRequestConverter(request);
        Result<List<OrderLine>> listResult = orderLineService.loadOrderLineList(orderLineLoadListRequest);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return new PageResult<>();
        }
        List<OrderLinePageQueryResponse> orderLinePageQueryResponses = listResult.getResult().stream().map(orderLine -> {
            LoadOrderRequest loadOrderRequest = new LoadOrderRequest();
            Integer forecastOrderStatus = null;
            Order order = null;
            if (!StringUtils.isEmpty(orderLine.getMainOrderId())) {
                loadOrderRequest.setId(orderLine.getMainOrderId());
                order = orderService.loadOrder(loadOrderRequest);
            }
            QueryForecastOrderDetailRequest queryForecastOrder = new QueryForecastOrderDetailRequest();
            if (!StringUtils.isEmpty(order.getFrontOrderId())) {
                queryForecastOrder.setId(order.getFrontOrderId());
                Result<QueryForecastOrderDetailReponse> result = forecastOrderQueryService.queryForecastOrder(queryForecastOrder);
                forecastOrderStatus = result.getResult().getForecastOrderSDO().getStatus();
            }
            return orderLinePageQueryResponseConverter(orderLine, order, forecastOrderStatus);
        }).collect(Collectors.toList());
        return PageResult.of(orderLinePageQueryResponses, listResult.getTotal());

    }

    @Override
    public OrderDetailDTO query(String id) {
        LoadOrderLineRequest loadOrderLineRequest = new LoadOrderLineRequest();
        if (!StringUtils.isEmpty(id)) {
            loadOrderLineRequest.setId(id);
        }
        OrderLine orderLine = orderLineService.loadOrderLine(loadOrderLineRequest);
        return OrderDetailDTOConverter(orderLine);
    }

    @Override
    public List<QuerySaleOrderLine> queryScItemInfo(QuerySaleOrderLineRequest request) {
        LoadOrderRequest loadOrderRequest = new LoadOrderRequest();
        loadOrderRequest.setId(request.getId());
        Order order = orderService.loadOrder(loadOrderRequest);
//        List<QuerySaleOrderLine> querySaleOrderLines = request.getSaleOrderLines().stream().map(saleOrderLine -> {

        //一 获取价格
        PriceQueryRequest priceQueryRequest = new PriceQueryRequest();

        List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();

        for (QuerySaleOrderLine orderLine : request.getSaleOrderLines()) {

            //转换参数
            String firstCategoryCode = null;
            String firstCategoryDesc = null;
            String secondCategoryCode = null;
            String secondCategoryDesc = null;

            if (StringUtils.isNotBlank(orderLine.getIdPath())) {
                String[] categoryIds = orderLine.getIdPath().split(">>");

                firstCategoryCode = categoryIds[0] == null ? null : categoryIds[0];
                if (categoryIds.length >= 2) {
                    secondCategoryCode = categoryIds[1] == null ? null : categoryIds[1];
                }

            }
            if (StringUtils.isNotBlank(orderLine.getCurrentPath())) {
                String[] categoryDescList = orderLine.getCurrentPath().split(">>");
                firstCategoryDesc = categoryDescList[0] == null ? null : categoryDescList[0];
                if (categoryDescList.length >= 2) {
                    secondCategoryDesc = categoryDescList[1] == null ? null : categoryDescList[1];
                }

            }
            orderLine.setFirstCategoryCode(firstCategoryCode);
            orderLine.setFirstCategoryDesc(firstCategoryDesc);
            orderLine.setSecondCategoryCode(secondCategoryCode);
            orderLine.setSecondCategoryDesc(secondCategoryDesc);


            DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
            dimensionPropertyInfoRequest.setPriceTypeId("ZP01");
            dimensionPropertyInfoRequest.setPriceUseDate(new Date());

            MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
            materialInfoRequest.setMaterialCode(orderLine.getGoodsId());
            //todo 货品组
            materialInfoRequest.setScItemGroupCode(order.getProductGroupCode());
            HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
            //todo 客户
            humanInfoRequest.setCustomerCode(order.getCustomerCode());
            humanInfoRequest.setCustomerSendAddressCode(order.getReceiveAddressCode());
            humanInfoRequest.setCustomerSaleAddressCode(order.getCustomerCode());
            PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
            placeInfoRequest.setChannelCode(order.getChannelCode());
            placeInfoRequest.setDepartmentCode(order.getDepartmentCode());
            placeInfoRequest.setSalesUnitCode(orderLine.getSaleUnit());
            placeInfoRequest.setOrgSalesOrganizationCode(order.getOrganizationCode());
            dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
            dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
            dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);
            dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
        }
        Map<String, String> features = new HashMap<>();
        features.put("codeFlag", "inner_code_to_out_code");
        priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList);
        priceQueryRequest.setFeatures(features);
        Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPriceExpand(priceQueryRequest);

        //modify by 皓晖 at 20211216 for 新建预报单选择最近使用超过50条货品不显示价格 begin
        if (!priceQueryResponseResult.isSuccess()) {
            throw new FacadeException(priceQueryResponseResult.getErrorCode(), "查询货品价格异常:" + priceQueryResponseResult.getMessage());
        } else if (org.apache.commons.collections.CollectionUtils.isEmpty(priceQueryResponseResult.getResult().getItemPriceResponseList())) {
            return request.getSaleOrderLines();
        }
        //modify by 皓晖 at 20211216 for 新建预报单选择最近使用超过50条货品不显示价格 end

        PriceQueryResponse result = priceQueryResponseResult.getResult();


        Map<String, Long> itemPriceMap = result.getItemPriceResponseList().stream().collect(HashMap::new, (m, v) -> m.put(v.getItemId(), v.getMoneyAmout()), HashMap::putAll);

        request.getSaleOrderLines().stream().forEach(querySaleOrderLine -> {
            querySaleOrderLine.setUnitPrice(itemPriceMap.get(querySaleOrderLine.getGoodsId()).toString());
        });

//            if (priceQueryResponseResult.getResult() != null) {
//            List<ItemPriceResponse> itemPriceResponseList = priceQueryResponseResult.getResult().getItemPriceResponseList();
//            ItemPriceResponse itemPriceResponse = itemPriceResponseList.get(0);
//            Long moneyAmout = itemPriceResponse.getMoneyAmout();
//            saleOrderLine.setUnitPrice("88");
//                if (moneyAmout != null) {
//                    saleOrderLine.setUnitPrice(String.valueOf(moneyAmout / 100));
//                }
//            }


        return request.getSaleOrderLines();
    }

    @Override
    public OrderDetailDTO queryOrderLine(QueryOrderLineRequest request) {
        OrderLine orderline = orderLineService.queryOrderLineByRequest(request);
        if (orderline == null) {
            return new OrderDetailDTO();
        }
        return OrderDetailDTOConverter(orderline);
    }


    private OrderDetailDTO OrderDetailDTOConverter(OrderLine orderLine) {
        OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
        if (null != orderLine.getId()) {
            orderDetailDTO.setId(String.valueOf(orderLine.getId()));
        }
        orderDetailDTO.setGoodsId(orderLine.getScItemId());
        orderDetailDTO.setGoodsName(orderLine.getScItemTitle());
        if (orderLine.getQuantity() != null) {
            orderDetailDTO.setQuantity(String.valueOf(orderLine.getQuantity()));
        }
        orderDetailDTO.setSaleUnit(orderLine.getSaleUnit());
        orderDetailDTO.setInventoryUnit(orderLine.getInventoryUnit());
        orderDetailDTO.setUnitConvert(orderLine.getUnitConvert());
        orderDetailDTO.setUnitPrice(orderLine.getUnitPrice());
        orderDetailDTO.setTotalAmount(orderLine.getShouldPayFee());
        if (null != orderLine.getProductationTime()) {
            orderDetailDTO.setProducteDate(String.valueOf(orderLine.getProductationTime()));
        }
        orderDetailDTO.setRemark(orderLine.getRemark());
        orderDetailDTO.setLineNum(orderLine.getSerialNumber());
        orderDetailDTO.setSaleQuantity(orderLine.getQuantity());
        if (!StringUtils.isEmpty(orderLine.getActivityPrice())) {
            orderDetailDTO.setActivityUnitPrice(orderLine.getActivityPrice());
        }
        if (!StringUtils.isEmpty(orderLine.getDeliveryAmount())) {
            orderDetailDTO.setCumulativeShipmentQuantity(Integer.parseInt(orderLine.getDeliveryAmount()));
        }
        orderDetailDTO.setActivityId(orderLine.getActivityCode());
        orderDetailDTO.setRejectReason(orderLine.getRefuseReasonCode());
        return orderDetailDTO;
    }


    private OrderLinePageQueryResponse orderLinePageQueryResponseConverter(OrderLine orderLine, Order order, Integer forecastOrderStatus) {
        OrderLinePageQueryResponse orderLinePageQueryResponse = new OrderLinePageQueryResponse();
        if (null != orderLine.getId()) {
            orderLinePageQueryResponse.setId(String.valueOf(orderLine.getId()));
        }
        if (!StringUtils.isEmpty(orderLine.getOrderLineTypeCode())) {
            String desc = OrderTypeStatus.of(Integer.parseInt(orderLine.getOrderLineTypeCode())).getDesc();
            orderLinePageQueryResponse.setOrderType(desc);
        }
        orderLinePageQueryResponse.setCustomerName(order.getCustomerName());
        orderLinePageQueryResponse.setCustomerCode(order.getCustomerCode());
        orderLinePageQueryResponse.setReceiveAddressCode(order.getReceiveAddressCode());
        orderLinePageQueryResponse.setReceiveDetailAddress(order.getReceiveDetailAddress());
        orderLinePageQueryResponse.setOrganizationCode(order.getOrganizationCode());
        orderLinePageQueryResponse.setOrganizationName(order.getOrganizationName());
        orderLinePageQueryResponse.setChannelCode(order.getChannelCode());
        orderLinePageQueryResponse.setChannelName(order.getChannelName());
        orderLinePageQueryResponse.setProductGroupCode(order.getProductGroupCode());
        orderLinePageQueryResponse.setProductGroupName(order.getProductGroupName());
        orderLinePageQueryResponse.setSaleChannelCode(order.getSaleChannelCode());
        orderLinePageQueryResponse.setSaleChannelName(order.getSaleChannelName());
        orderLinePageQueryResponse.setDepartmentCode(order.getDepartmentCode());
        orderLinePageQueryResponse.setDepartmentName(order.getDepartmentName());
        //TODO  客户组
        //TODO  销售地区
        orderLinePageQueryResponse.setCreatorId(order.getCreator());
        orderLinePageQueryResponse.setCreatorName(order.getCreatorName());

        orderLinePageQueryResponse.setFrontOrderId(order.getFrontOrderId());
        orderLinePageQueryResponse.setCustomerReferenceNo(order.getCustomerReferenceNo());
        orderLinePageQueryResponse.setOrderRemark(order.getRemark());
        if (orderLine.getQuantity() != null) {
            orderLinePageQueryResponse.setForecastQuantity(String.valueOf(orderLine.getQuantity()));
        }
        if (order.getId() != null) {
            orderLinePageQueryResponse.setOrderId(String.valueOf(order.getId()));
        }
        if (order.getGmtCreate() != null) {
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String orderGmtCreate = spf.format(order.getGmtCreate());
            orderLinePageQueryResponse.setOrderGmtCreate(orderGmtCreate);
        }
        if (orderLine.getGmtCreate() != null) {
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String orderLineGmtCreate = spf.format(order.getGmtCreate());
            orderLinePageQueryResponse.setGmtCreate(orderLineGmtCreate);
        }
        if (order.getCustomerExpectDate() != null) {
            SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String deliveryDate = spf.format(order.getCustomerExpectDate());
            orderLinePageQueryResponse.setDeliveryDate(deliveryDate);
        }
        orderLinePageQueryResponse.setOrderReason(order.getCreateReason());
        orderLinePageQueryResponse.setScItemId(orderLine.getScItemId());
        orderLinePageQueryResponse.setScItemTitle(orderLine.getScItemTitle());
        if (orderLine.getQuantity() != null) {
            orderLinePageQueryResponse.setOrderQuantity(String.valueOf(orderLine.getQuantity()));
        }
        orderLinePageQueryResponse.setSalesUnit(orderLine.getSaleUnit());
        if (!StringUtils.isEmpty(orderLine.getFeatures())) {
            Map<String, String> orderFeatureMap = (Map) JSONObject.parse(orderLine.getFeatures());
            if (MapUtils.isNotEmpty(orderFeatureMap)) {
                if (orderFeatureMap.get(SaleOrderConstants.SHIP_POINT) != null) {
                    orderLinePageQueryResponse.setShipPoint(orderFeatureMap.get(SaleOrderConstants.SHIP_POINT));
                }
                if (orderFeatureMap.get(SaleOrderConstants.INVENTORY_CODE) != null) {
                    orderLinePageQueryResponse.setSAPInventoryPoint(orderFeatureMap.get(SaleOrderConstants.INVENTORY_CODE));
                }
                if (orderFeatureMap.get(SaleOrderConstants.FACTORY_CODE) != null) {
                    orderLinePageQueryResponse.setSAPFactoryCode(orderFeatureMap.get(SaleOrderConstants.FACTORY_CODE));
                }
                if (orderFeatureMap.get(SaleOrderConstants.NK_PRICE) != null) {
                    orderLinePageQueryResponse.setNkPrice(orderFeatureMap.get(SaleOrderConstants.NK_PRICE));
                }
                if (orderFeatureMap.get(SaleOrderConstants.DCT_BEFORE_PRICE) != null) {
                    orderLinePageQueryResponse.setDctBeforePrice(orderFeatureMap.get(SaleOrderConstants.DCT_BEFORE_PRICE));
                }
                if (orderFeatureMap.get(SaleOrderConstants.DISCOUNT) != null) {
                    orderLinePageQueryResponse.setDiscount(orderFeatureMap.get(SaleOrderConstants.DISCOUNT));
                }
            }
        }
        orderLinePageQueryResponse.setRefuseReasonCode(orderLine.getRefuseReasonCode());
        orderLinePageQueryResponse.setRefuseReasonName(orderLine.getRefuseReasonName());
        if (order.getStatus() != null) {
            orderLinePageQueryResponse.setOrderStatus(String.valueOf(order.getStatus()));
        }
        if (null != forecastOrderStatus) {
            orderLinePageQueryResponse.setForecastStatus(String.valueOf(forecastOrderStatus));
        }

        return orderLinePageQueryResponse;
    }

    private OrderLineLoadListRequest orderLineLoadListRequestConverter(OrderLinePageQueryRequest request) {
        OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
        if (!StringUtils.isEmpty(request.getId())) {
            orderLineLoadListRequest.setId(Long.parseLong(request.getId()));
        }
        orderLineLoadListRequest.setOrderLineTag(request.getOrderLineTag());
        orderLineLoadListRequest.setOrderLineType(request.getOrderType());
        orderLineLoadListRequest.setOrderLineTypeCode(request.getOrderTypeCode());
        orderLineLoadListRequest.setCustomerCode(request.getCustomer());
        orderLineLoadListRequest.setScItemId(request.getScItemId());
        orderLineLoadListRequest.setScItemTitle(request.getScItemTitle());
        orderLineLoadListRequest.setCreatorName(request.getCreatorName());
        orderLineLoadListRequest.setModifierName(request.getModifierName());

        //TODO  查询条件待完善
        orderLineLoadListRequest.setLimit(request.getLimit());
        orderLineLoadListRequest.setStart(request.getStart());
        orderLineLoadListRequest.setDir("gmtCreate");
        orderLineLoadListRequest.setAsc(false);
        return orderLineLoadListRequest;
    }

    @Override
    @RepositoryInvoker(errorCode = "ORDER-A-001-01-16-004")
    public Result<List<OrderLinePageQueryResponse>> pageQueryES(PageQueryOrderLineESListRequest request) {
        request.setDir("sub_gmt_create");

        //单据创建日期
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(request.getOrderTime())) {

            request.setGmtCreateStartTime(request.getOrderTime().get(0) == null ? null : DateUtils.string2Date(request.getOrderTime().get(0)));
            request.setGmtCreateEndTime(request.getOrderTime().get(1) == null ? null : DateUtils.string2Date(request.getOrderTime().get(1)));
        }

        //单据修改日期
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(request.getUpdateTime())) {
            request.setUpdateStartTime(request.getUpdateTime().get(0) == null ? null : DateUtils.string2Date(request.getUpdateTime().get(0)));
            request.setUpdateEndTime(request.getUpdateTime().get(1) == null ? null : DateUtils.string2Date(request.getUpdateTime().get(1)));
        }

        Result<List<ObtcSaleOrderLineIndex>> listResult = obtcSaleOrderLineIndexService.loadOrderLineListES(request);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return new Result<>();
        }
        List<OrderLinePageQueryResponse> orderLinePageQueryResponses = listResult.getResult().stream()
                .map(this::orderLinePageQueryResponseConverterOne).collect(Collectors.toList());
        return Result.listSuccess(orderLinePageQueryResponses, listResult.getTotal());

    }

    private OrderLinePageQueryResponse orderLinePageQueryResponseConverterOne(ObtcSaleOrderLineIndex obtcSaleOrderLineIndex) {
        OrderLinePageQueryResponse orderLinePageQueryResponse = new OrderLinePageQueryResponse();
        if (null != obtcSaleOrderLineIndex.getSubId()) {
            orderLinePageQueryResponse.setId(String.valueOf(obtcSaleOrderLineIndex.getSubId()));
        }
        if (!StringUtils.isEmpty(obtcSaleOrderLineIndex.getMainOrderType())) {
            String desc = SaleOrderTag.of(obtcSaleOrderLineIndex.getMainOrderType()).getDesc();
            orderLinePageQueryResponse.setOrderType(desc);
        }
        orderLinePageQueryResponse.setCustomerName(obtcSaleOrderLineIndex.getMainCustomerName());
        orderLinePageQueryResponse.setCustomerCode(obtcSaleOrderLineIndex.getMainCustomerCode());
        orderLinePageQueryResponse.setReceiveAddressCode(obtcSaleOrderLineIndex.getMainReceiveAddressCode());
        orderLinePageQueryResponse.setReceiveDetailAddress(obtcSaleOrderLineIndex.getMainReceiveDetailAddress());
        orderLinePageQueryResponse.setOrganizationCode(obtcSaleOrderLineIndex.getMainOrganizationCode());
        orderLinePageQueryResponse.setOrganizationName(obtcSaleOrderLineIndex.getMainOrganizationName());
        orderLinePageQueryResponse.setChannelCode(obtcSaleOrderLineIndex.getMainChannelCode());
        orderLinePageQueryResponse.setChannelName(obtcSaleOrderLineIndex.getMainChannelName());
        orderLinePageQueryResponse.setProductGroupCode(obtcSaleOrderLineIndex.getMainProductGroupCode());
        orderLinePageQueryResponse.setProductGroupName(obtcSaleOrderLineIndex.getMainProductGroupName());
        orderLinePageQueryResponse.setSaleChannelCode(obtcSaleOrderLineIndex.getMainSaleChannelCode());
        orderLinePageQueryResponse.setSaleChannelName(obtcSaleOrderLineIndex.getMainSaleChannelName());
        orderLinePageQueryResponse.setDepartmentCode(obtcSaleOrderLineIndex.getMainDepartmentCode());
        orderLinePageQueryResponse.setDepartmentName(obtcSaleOrderLineIndex.getMainDepartmentName());
        orderLinePageQueryResponse.setCreatorId(obtcSaleOrderLineIndex.getMainCreator());
        orderLinePageQueryResponse.setCreatorName(obtcSaleOrderLineIndex.getMainCreatorName());
        orderLinePageQueryResponse.setOrderLineRemark(obtcSaleOrderLineIndex.getSubRemark());
        orderLinePageQueryResponse.setOutLineId(obtcSaleOrderLineIndex.getSubOuterOrderLineId());

        orderLinePageQueryResponse.setFrontOrderId(obtcSaleOrderLineIndex.getMainFrontOrderId());
        orderLinePageQueryResponse.setCustomerReferenceNo(obtcSaleOrderLineIndex.getMainCustomerReferenceNo());
        orderLinePageQueryResponse.setOrderRemark(obtcSaleOrderLineIndex.getMainRemark());
        orderLinePageQueryResponse.setHeaderRemark(obtcSaleOrderLineIndex.getMainRemark());
        orderLinePageQueryResponse.setDeliveryAmount(obtcSaleOrderLineIndex.getSubDeliveryAmount());
        orderLinePageQueryResponse.setGoodsCode(obtcSaleOrderLineIndex.getSubScItemOutCode());

        if (obtcSaleOrderLineIndex.getMainId() != null) {
            orderLinePageQueryResponse.setOrderId(String.valueOf(obtcSaleOrderLineIndex.getMainId()));
        }
        if (obtcSaleOrderLineIndex.getMainGmtCreate() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(obtcSaleOrderLineIndex.getMainGmtCreate());
            SimpleDateFormat spf = new SimpleDateFormat(DateUtils.PATTEN_YMD);
            String orderGmtCreate = spf.format(calendar.getTime());
            orderLinePageQueryResponse.setOrderGmtCreate(orderGmtCreate);
        }
        if (obtcSaleOrderLineIndex.getSubGmtCreate() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(obtcSaleOrderLineIndex.getSubGmtCreate());
            SimpleDateFormat spf = new SimpleDateFormat(DateUtils.PATTEN_YMD);
            String orderLineGmtCreate = spf.format(calendar.getTime());
            orderLinePageQueryResponse.setGmtCreate(orderLineGmtCreate);
            // 按产品要求页面创建时间字段加时分秒、为了不影响其它调用接口的使用，新增gmtCreateDate字段
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DateUtils.DATETIME_FORMAT);
            orderLinePageQueryResponse.setGmtCreateDate(simpleDateFormat.format(calendar.getTime()));
        }
        if (obtcSaleOrderLineIndex.getMainCustomerExpectDate() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(obtcSaleOrderLineIndex.getMainCustomerExpectDate());
            SimpleDateFormat spf = new SimpleDateFormat(DateUtils.PATTEN_YMD);
            String deliveryDate = spf.format(calendar.getTime());
            orderLinePageQueryResponse.setDeliveryDate(deliveryDate);
        }
        orderLinePageQueryResponse.setScItemId(obtcSaleOrderLineIndex.getSubScItemId());
        orderLinePageQueryResponse.setScItemTitle(obtcSaleOrderLineIndex.getSubScItemTitle());
        if (obtcSaleOrderLineIndex.getSubQuantity() != null) {
            orderLinePageQueryResponse.setOrderQuantity(String.valueOf(obtcSaleOrderLineIndex.getSubQuantity()));
        }
        orderLinePageQueryResponse.setSalesUnit(obtcSaleOrderLineIndex.getSubSaleUnit());
        orderLinePageQueryResponse.setSalesUnitName(obtcSaleOrderLineIndex.getSubSaleUnitName());
        orderLinePageQueryResponse.setOrderReason(obtcSaleOrderLineIndex.getMainCreateReason());
        orderLinePageQueryResponse.setOrderBizId(obtcSaleOrderLineIndex.getMainOrderBizId());
//        if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubFrontOrderLineType())) {
//            orderLinePageQueryResponse.setForecastOrderType(SaleOrderTag.of(obtcSaleOrderLineIndex.getSubFrontOrderLineType()).getDesc());
//        }
        orderLinePageQueryResponse.setSalesOrderLineNo(obtcSaleOrderLineIndex.getSubSerialNumber());
        orderLinePageQueryResponse.setForecastOrderLineNo(obtcSaleOrderLineIndex.getSubSerialNumber());
        orderLinePageQueryResponse.setCategory(obtcSaleOrderLineIndex.getSubCategoryDesc());
        orderLinePageQueryResponse.setCategoryChildren(obtcSaleOrderLineIndex.getSubCategoryChildDesc());
        orderLinePageQueryResponse.setSAPFactory(obtcSaleOrderLineIndex.getMainFactoryCode());
        orderLinePageQueryResponse.setRefuseReasonName(obtcSaleOrderLineIndex.getSubRefuseReasonName());
        orderLinePageQueryResponse.setActivityId(obtcSaleOrderLineIndex.getSubActivityId());
        orderLinePageQueryResponse.setActivityName(obtcSaleOrderLineIndex.getSubActivityName());
        orderLinePageQueryResponse.setSapSaleOrderId(obtcSaleOrderLineIndex.getMainOuterOrderId());
        //订单常规价格
        orderLinePageQueryResponse.setOrderRegularPrice(obtcSaleOrderLineIndex.getSubUnitPrice());
        //活动价格
        if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubActivityPrice())) {
            orderLinePageQueryResponse.setActivityPrice(Long.parseLong(obtcSaleOrderLineIndex.getSubActivityPrice()));
        }
        //订单折后金额(KZWI1)  小计金额
        if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubShouldPayFee())) {
            orderLinePageQueryResponse.setAfterDiscountAmount(Long.parseLong(obtcSaleOrderLineIndex.getSubShouldPayFee()));
        }
        //订单折后价格(KZWI1)
        if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubShouldPayFee()) && null != obtcSaleOrderLineIndex.getSubQuantity()) {
            BigDecimal a = new BigDecimal(obtcSaleOrderLineIndex.getSubShouldPayFee());
            BigDecimal b = BigDecimal.valueOf(obtcSaleOrderLineIndex.getSubQuantity());
            if (!b.equals(BigDecimal.ZERO)) {
                BigDecimal divide = a.divide(b, 2, BigDecimal.ROUND_HALF_UP);
                orderLinePageQueryResponse.setDiscountedPrice(String.valueOf(divide));
            }
        }
        //TODO 后期处理进行落库
        if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getMainCreateReason())) {
            QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
            queryDictionaryRequest.setDictCode(ORDER_REASON_TYPE);
            Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
            dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                if (x.getValueData().equals(obtcSaleOrderLineIndex.getMainCreateReason())) {
                    orderLinePageQueryResponse.setOrderReasonName(x.getValueName());
                }
            });
        }

        //子单features中取值
        if (!StringUtils.isEmpty(obtcSaleOrderLineIndex.getSubFeatures())) {
            //设置子单的features
            orderLinePageQueryResponse.setOrderLineFeatures(obtcSaleOrderLineIndex.getSubFeatures());

            Map<String, String> subFeatures = JSONObject.parseObject(obtcSaleOrderLineIndex.getSubFeatures(), Map.class);
            //Map<String,String> orderFeatureMap = (Map)JSONObject.parse(obtcSaleOrderLineIndex.getSubFeatures());
            if (MapUtils.isNotEmpty(subFeatures)) {
                //基本单位交货单数量
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.BASIC_QTY))) {
                    orderLinePageQueryResponse.setDeliveryQuantityAndBaseUnit(trimEndZeroOfBigDecimal(new BigDecimal(subFeatures.get(SaleOrderConstants.BASIC_QTY).trim())));
                }

                //预报数量
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.FORECAST_QUANTITY))) {
                    orderLinePageQueryResponse.setForecastQuantity(subFeatures.get(SaleOrderConstants.FORECAST_QUANTITY));
                }
                //预报订单类型编码
                if (subFeatures.get(SaleOrderConstants.FRONT_ORDER_LINE_TYPE) != null) {
                    orderLinePageQueryResponse.setForecastOrderType(SaleOrderTag.of(subFeatures.get(SaleOrderConstants.FRONT_ORDER_LINE_TYPE)).getDesc());
                }
                //装运点
                if (subFeatures.get(SaleOrderConstants.SHIP_POINT) != null) {
                    orderLinePageQueryResponse.setShipPoint(subFeatures.get(SaleOrderConstants.SHIP_POINT));
                }
                //交货库存地点
                if (subFeatures.get(SaleOrderConstants.INVENTORY_CODE) != null) {
                    orderLinePageQueryResponse.setSAPInventoryPoint(subFeatures.get(SaleOrderConstants.INVENTORY_CODE));
                }
                //交货工厂
                if (subFeatures.get(SaleOrderConstants.FACTORY_CODE) != null) {
                    orderLinePageQueryResponse.setSAPFactoryCode(subFeatures.get(SaleOrderConstants.FACTORY_CODE));
                    orderLinePageQueryResponse.setSAPFactory(orderLinePageQueryResponse.getSAPFactoryCode());
                }
                //奶卡价格(ZP02)
                if (subFeatures.get(SaleOrderConstants.NK_PRICE) != null) {
                    orderLinePageQueryResponse.setNkPrice(subFeatures.get(SaleOrderConstants.NK_PRICE));
                }
//                //订单常规价格(ZP01)
//                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.ORDER_REGULAR_PRICE))) {
//                    orderLinePageQueryResponse.setOrderRegularPrice(subFeatures.get(SaleOrderConstants.ORDER_REGULAR_PRICE));
//                }
                //订单含返点常规价格(ZP01+ZK18)
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.TURNING_PRICE))) {
                    BigDecimal bigDecimal = new BigDecimal(subFeatures.get(SaleOrderConstants.TURNING_PRICE));
                    orderLinePageQueryResponse.setRegularPriceWithRebate(Long.parseLong(String.valueOf(bigDecimal)));
                }

                //订单折前价格(ZK99)
                if (subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE) != null) {
                    orderLinePageQueryResponse.setDctBeforePrice(subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE));
                }

                //订单含返点常规金额(ZP01+ZK18)
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.TURNING_PRICE)) && null != obtcSaleOrderLineIndex.getSubQuantity()) {
                    BigDecimal a = new BigDecimal(subFeatures.get(SaleOrderConstants.TURNING_PRICE));
                    BigDecimal b = BigDecimal.valueOf(obtcSaleOrderLineIndex.getSubQuantity());
                    BigDecimal multiply = a.multiply(b);
                    orderLinePageQueryResponse.setRegularAmountWithRebate(Long.parseLong(multiply.toString()));
                }
                //订单折前金额(ZK99)
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE))) {
                    BigDecimal a = new BigDecimal(subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE));
                    BigDecimal b = BigDecimal.valueOf(obtcSaleOrderLineIndex.getSubQuantity());
                    BigDecimal multiply = a.multiply(b);
                    orderLinePageQueryResponse.setBeforeDiscountedAmount(Long.parseLong(multiply.toString()));
                }
                //订单固定折扣(ZK01)
                if (subFeatures.get(SaleOrderConstants.DISCOUNT) != null) {
                    orderLinePageQueryResponse.setDiscount(subFeatures.get(SaleOrderConstants.DISCOUNT));
                }
                //交货单号
                if (subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_ID) != null) {
                    orderLinePageQueryResponse.setDeliveryOrderId(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_ID));
                }
                //交货单行号
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_LINE_NO)) {
                    orderLinePageQueryResponse.setDeliveryNoteLineItemNo(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_LINE_NO));
                }
                //交货单创建人
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_CREATOR)) {
                    orderLinePageQueryResponse.setDeliveryNoteCreator(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_CREATOR));
                }
                //交货单创建日期
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_CREAT_DATE)) {
                    orderLinePageQueryResponse.setDeliveryNoteCreateDate(DateUtils.string2String(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_CREAT_DATE)));
                }
                //发货过账日期
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_DATE))) {
                    orderLinePageQueryResponse.setShipmentPostingDate(DateUtils.string2String(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_DATE)));
                }
                //交货单数量
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_QTY)) {
                    orderLinePageQueryResponse.setDeliveryOrdersQuality(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_QTY));
                }
                //POD状态
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_STATUS)) {
                    orderLinePageQueryResponse.setPodStatus(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_STATUS));
                }
                //POD后数量
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_QTY)) {
                    orderLinePageQueryResponse.setAfterPodQuality(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_QTY));
                }
                //交货单折前金额(ZK99)
                //POD数量不为空的计算逻辑
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_QTY) && null != subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE)) {
                    BigDecimal a = new BigDecimal(subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE));
                    BigDecimal b = new BigDecimal(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_QTY));
                    BigDecimal multiply = a.multiply(b).setScale(0,RoundingMode.HALF_UP);;
                    orderLinePageQueryResponse.setBeforeDiscountedAmountOfDeliveryNote(multiply.longValue());
                } else {
                    //POD数量为空的计算逻辑
                    if (null != subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE) && null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_QTY)) {
                        BigDecimal a = new BigDecimal(subFeatures.get(SaleOrderConstants.DCT_BEFORE_PRICE));
                        BigDecimal b = new BigDecimal(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_QTY));
                        BigDecimal multiply = a.multiply(b).setScale(0,RoundingMode.HALF_UP);
                        orderLinePageQueryResponse.setBeforeDiscountedAmountOfDeliveryNote(multiply.longValue());
                    }
                }

                //交货单折后金额(KZWI1)
                //POD数量不为空的计算逻辑
                if (null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_QTY) && StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubShouldPayFee())) {
                    BigDecimal b = new BigDecimal(obtcSaleOrderLineIndex.getSubShouldPayFee());
                    BigDecimal multiply = b.multiply(new BigDecimal(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_POD_QTY)));
                    if (null != obtcSaleOrderLineIndex.getSubQuantity()) {
                        BigDecimal divide = multiply.divide(new BigDecimal(obtcSaleOrderLineIndex.getSubQuantity()), 0, BigDecimal.ROUND_HALF_UP);
                        orderLinePageQueryResponse.setAfterDiscountAmountOfDeliveryNote(divide.longValue());
                    }
                } else {
                    //POD数量为空的计算逻辑
                    if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubShouldPayFee()) && null != subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_QTY)) {
                        BigDecimal b = new BigDecimal(obtcSaleOrderLineIndex.getSubShouldPayFee());
                        BigDecimal multiply = b.multiply(new BigDecimal(subFeatures.get(SaleOrderConstants.DELIVERY_ORDER_QTY)));
                        if (null != obtcSaleOrderLineIndex.getSubQuantity()) {
                            BigDecimal divide = multiply.divide(new BigDecimal(obtcSaleOrderLineIndex.getSubQuantity()), 0, BigDecimal.ROUND_HALF_UP);
                            orderLinePageQueryResponse.setAfterDiscountAmountOfDeliveryNote(divide.longValue());
                        }
                    }
                }

                //发票号
                if (null != subFeatures.get(SaleOrderConstants.INVOICE_ID)) {
                    orderLinePageQueryResponse.setReceiptNo(subFeatures.get(SaleOrderConstants.INVOICE_ID));
                }
                //发票行项目号
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_NO))) {
                    orderLinePageQueryResponse.setReceiptLineItemNo(subFeatures.get(SaleOrderConstants.INVOICE_NO));
                }
                //发票类型
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_TYPE))) {
                    orderLinePageQueryResponse.setReceiptType(subFeatures.get(SaleOrderConstants.INVOICE_TYPE));
                }
                //出具发票日期
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_DATE))) {
                    orderLinePageQueryResponse.setReceiptDate(DateUtils.string2String(subFeatures.get(SaleOrderConstants.INVOICE_DATE)));
                }
                //发票创建人
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_CREATOR))) {
                    orderLinePageQueryResponse.setReceiptCreator(subFeatures.get(SaleOrderConstants.INVOICE_CREATOR));
                }
                //发票创建日期
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_CREATE_TIME))) {
                    orderLinePageQueryResponse.setReceiptCreateDate(DateUtils.string2String(subFeatures.get(SaleOrderConstants.INVOICE_CREATE_TIME)));
                }
                //发票价格
                /*if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_PRICE))) {
                    orderLinePageQueryResponse.setReceiptPrice(Long.parseLong(subFeatures.get(SaleOrderConstants.INVOICE_PRICE)));
                }*/
                //发票数量
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_QTY))) {
                    orderLinePageQueryResponse.setReceiptQuantity(subFeatures.get(SaleOrderConstants.INVOICE_QTY));
                }

                //发票金额
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_ZK01_FEE))) {

                    //折扣金额
                    if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_QTY))) {
                        //BigDecimal a = new BigDecimal(subFeatures.get(SaleOrderConstants.INVOICE_PRICE));
//                        BigDecimal invoiceQtyDec = new BigDecimal(subFeatures.get(SaleOrderConstants.INVOICE_QTY));
//                        Long originalReceiptAmount= null;
//                        try {
//                            originalReceiptAmount = a.multiply(invoiceQtyDec).longValue();
//                        } catch (Exception e) {
//                            log.info("Long originalReceiptAmount:",e);
//                        }

                        //Long actualReceiptAmount=Long.parseLong(subFeatures.get(SaleOrderConstants.INVOICE_ZK01_FEE));
                        //和PD确认，ReceiptZk01Amount改为折扣值，PD要求是负数
                        //orderLinePageQueryResponse.setReceiptZk01Amount(actualReceiptAmount-originalReceiptAmount);

                        //和PD确认，发票金额直接使用折扣金额
                        BigDecimal invoiceQtyDec = new BigDecimal(subFeatures.get(SaleOrderConstants.INVOICE_QTY));
                        Long zkReceiptAmount = Long.parseLong(subFeatures.get(SaleOrderConstants.INVOICE_ZK01_FEE));
                        orderLinePageQueryResponse.setReceiptAmount(zkReceiptAmount);
                        if (orderLinePageQueryResponse.getReceiptQuantity() != null && !invoiceQtyDec.equals(BigDecimal.ZERO)) {
                            BigDecimal zkReceiptAmountDec = new BigDecimal(zkReceiptAmount);
                            BigDecimal zkPrice = zkReceiptAmountDec.divide(invoiceQtyDec, 2, RoundingMode.HALF_UP);
                            BigDecimal multiply = zkPrice.multiply(new BigDecimal(100));
                            orderLinePageQueryResponse.setReceiptPrice(multiply.longValue());
                        }
                    }

                }

                //发票折扣金额
                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.INVOICE_ID))) {
                    if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubShouldPayFee()) && null != orderLinePageQueryResponse.getBeforeDiscountedAmount()) {
                        orderLinePageQueryResponse.setReceiptZk01Amount(Long.parseLong(obtcSaleOrderLineIndex.getSubShouldPayFee()) - orderLinePageQueryResponse.getBeforeDiscountedAmount());
                    }
                }

                //设置活动行号
                String activityNumber = null;
                String activityId = null;
                if (StringUtils.isNotBlank(subFeatures.get("activityDteails"))) {
                    List<ActivitySDO> activitySDOS = JSONObject.parseArray(subFeatures.get("activityDteails"), ActivitySDO.class);
                    if (org.apache.commons.collections.CollectionUtils.isNotEmpty(activitySDOS)) {
                        List<String> collect = activitySDOS.stream().map(ActivitySDO::getActivityTermid).collect(Collectors.toList());
                        activityNumber = collect.stream().collect(Collectors.joining("/"));

                        List<String> collectOne = activitySDOS.stream().map(ActivitySDO::getActivityCode).collect(Collectors.toList());
                        activityId = collectOne.stream().collect(Collectors.joining("/"));
                    }
                    orderLinePageQueryResponse.setActivityLineNo(activityNumber);
                    orderLinePageQueryResponse.setActivityId(activityId);
                }
//                if (Objects.nonNull(subFeatures.get("activityDteails"))) {
//                    List<ActivitySDO> activitySDOS = JSONObject.parseArray(subFeatures.get("activityDteails"), ActivitySDO.class);
//
//                    BigDecimal bigDecimal = new BigDecimal(subFeatures.get(SaleOrderConstants.ACTIVITY_PRICE));
//                    orderLinePageQueryResponse.setActivityPrice(Long.parseLong(String.valueOf(bigDecimal)));
//                }
//                //活动行号
//                if (StringUtils.isNotBlank(subFeatures.get(SaleOrderConstants.ACTIVITY_LINE_NO))) {
//                    orderLinePageQueryResponse.setActivityLineNo(subFeatures.get(SaleOrderConstants.ACTIVITY_LINE_NO));
//                }

            }
        }

        //主单features中取值
        if (!StringUtils.isEmpty(obtcSaleOrderLineIndex.getMainFeatures())) {
            Map<String, String> mainFeatures = JSONObject.parseObject(obtcSaleOrderLineIndex.getMainFeatures(), Map.class);
            if (MapUtils.isNotEmpty(mainFeatures)) {
                if (mainFeatures.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID) != null) {
                    orderLinePageQueryResponse.setFrontOrderBizId(mainFeatures.get(SaleOrderConstants.FRONT_ORDER_BIZ_ID));
                }
            }
        }
        orderLinePageQueryResponse.setRefuseReasonCode(obtcSaleOrderLineIndex.getSubRefuseReasonCode());
        if (StringUtils.isNotBlank(obtcSaleOrderLineIndex.getSubRefuseReasonCode())) {
            QueryDictionaryRequest queryDictionaryRequest = new QueryDictionaryRequest();
            queryDictionaryRequest.setDictCode(REFUSE_REASON);
            Result<DictionarySDO> dictionarySDOResult = dictionaryQueryService.querySingle(queryDictionaryRequest);
            dictionarySDOResult.getResult().getDictValueList().stream().forEach(x -> {
                if (x.getValueData().equals(obtcSaleOrderLineIndex.getSubRefuseReasonCode())) {
                    orderLinePageQueryResponse.setRefuseReasonName(x.getValueName());
                }
            });
        }
        if (obtcSaleOrderLineIndex.getMainStatus() != null) {
            orderLinePageQueryResponse.setOrderStatus(String.valueOf(obtcSaleOrderLineIndex.getMainStatus()));
            String desc = OrderStatus.of(Integer.parseInt(String.valueOf(obtcSaleOrderLineIndex.getMainStatus()))).getDesc();
            orderLinePageQueryResponse.setStatus(desc);
        }

        return orderLinePageQueryResponse;
    }

    @Override
    public Result<Long> countOrderNumber(PageQueryOrderLineESListRequest request) {
        Calendar cale = Calendar.getInstance();
        cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 1);

        log.info("++++" + DateUtils.getFirstTime(cale.getTime()));
        //查询当前月份创建的销售订单
        request.setGmtCreateStartTime(DateUtils.getFirstTime(cale.getTime()));
        Result<List<ObtcSaleOrderLineIndex>> listResult = obtcSaleOrderLineIndexService.loadOrderLineListES(request);
        if (!CollectionUtils.isEmpty(listResult.getResult())) {
            //查询销售订单的总数量
            long sum = Nullable.stream(listResult.getResult()).filter(it -> !Objects.isNull(it.getSubQuantity())).mapToLong(it -> it.getSubQuantity()).sum();
            return Result.success(sum);
        }
        return Result.success(0L);
    }

    @Override
    public Result<AmountResponse> searchOrderLineList(SearchOrderLineListRequest request) {
        Result<List<ObtcSaleOrderLineIndex>> result = obtcSaleOrderLineIndexService.searchOrderLineIByEs(request);
        AmountResponse response = new AmountResponse();
        AtomicReference<Double> basicUnitQty = new AtomicReference<>(0.0);
        if (result != null && !CollectionUtils.isEmpty(result.getResult())) {
            //累计数量

            result.getResult().stream().forEach(obtcSaleOrderLineIndex -> {
                if (obtcSaleOrderLineIndex.getSubDeliveryAmount() != null) {
                    Double qty = Double.parseDouble(obtcSaleOrderLineIndex.getSubDeliveryAmount()) / Double.parseDouble(obtcSaleOrderLineIndex.getSubUnitConvert());
                    basicUnitQty.updateAndGet(v -> v + qty);
//                    basicUnitQty.add(new BigDecimal(qty));
                }

            });


        }

        response.setBasicDeliveryAmountTotal(new BigDecimal(basicUnitQty.get()).setScale(3, RoundingMode.DOWN).toString());
        return Result.success(response);
    }

    public static String trimEndZeroOfBigDecimal(BigDecimal bigDecimal) {
        String val = "";
        if (bigDecimal == null) {
            return val;
        } else {
            val = String.valueOf(bigDecimal);
        }
        if (val.indexOf(".") > 0) {
            // 去掉后面无用的零
            val = val.replaceAll("0+?$", "");
            // 如小数点后面全是零则去掉小数点
            val = val.replaceAll("[.]$", "");
        }
        return val;
    }
}
